
import ConnectWallet from "@/components/connectWallet"
import { useProviderHook, useUpdateAddress } from "@/utils/hooks.tsx";
import { chainIdToNativeSymbol } from "@/utils/wallet-util";
import { Button, Card, Collapse } from "antd";
import { useEffect, useRef, useState } from "react";
import { useAppDispatch, useAppSelector } from '@/store/hooks';
import { setChainId, setNativeSymbol, updateBalance } from "@/store/slices/walletSlice";
import type { RootState } from "@/store";
import { ethers } from "ethers";
import { Address } from "@ant-design/web3";
import TransactionCoin from "@/components/transactionCoin";
let transactionHashList: string[] = [];
const pageSize = 20
const Index = () => {
  const { provider } = useProviderHook();
  const TransactionCoinRef = useRef<{ setOpen: (open: boolean) => void } | null>(null);
  const dispatch = useAppDispatch();
  const walletState = useAppSelector((state: RootState) => state.wallet);
  const [transactionList, setTransactionList] = useState<ethers.providers.TransactionResponse[]>([]);
  const updateAddressHook = useUpdateAddress()
  useEffect(() => {
    console.log('===provider===11', provider)
    if (provider) {
      initPage()
    }
  }, [provider])
  useEffect(() => {
    observerEthereum()
  }, [])
  const observerEthereum = async () => {
    window.ethereum.on('message', (message: {
      type: string;
      data: any;
    }) => {
      console.log('收到消息:', message);
    });
    window.ethereum.on('accountsChanged', (accounts: string[]) => {
      console.log('账户变化:', accounts);
      updateAddressHook(accounts)
      // 处理账户变化逻辑
    });
    window.ethereum.on('chainChanged', (chainId: string) => {
      console.log('链ID变化:', chainId);
      // 处理链变化逻辑
    });
  }
  const initPage = async () => {
    if (provider) {
      const chainId = await window.ethereum.request({ method: "eth_chainId" })
      const nativeSymbol = chainIdToNativeSymbol[chainId as string] || 'ETH'
      dispatch(setChainId(chainId));
      dispatch(setNativeSymbol(nativeSymbol));
      const balance = await provider.getBalance(walletState.address || '');
      let etherString = ethers.utils.formatEther(balance);
      dispatch(updateBalance(etherString));
      getTransactionList();
    }
  }
  const getTransactionList = async () => {
    if (provider) {
      const endBlock = await provider.getBlockNumber();
      const targetAddress = ethers.utils.getAddress(walletState.address || '');
      const block = await provider.getBlock(endBlock);
      transactionHashList = block.transactions;
      let sliceList = transactionHashList.slice(0, pageSize);
      let list = await Promise.all(sliceList.map(async (address) => {
        const transaction = await provider.getTransaction(address)
        return transaction
      }))
      setTransactionList([...list])
      console.log('===transactionList===', block, list)
    }
  }
  return <>
    <ConnectWallet/>
    <div className="w-screen flex pt-[20px]">
      <div className="flex-1"></div>
      <div className="w-[900px]">
        <Card>
          <div className="mt-[16px] text-[32px] font-bold leading-[32px] text-center">
            {walletState.nativeSymbol}
            <span>{ walletState.balance }</span>
          </div>
        </Card>
        <Card className="mt-[20px]" title="交易记录" extra={<Button type="link" onClick={() => TransactionCoinRef.current?.setOpen(true)}>发起交易</Button>}>
          <Collapse items={transactionList.map(item => {
            return {
              key: item.hash || '',
              label: <Address ellipsis tooltip={false} address={item.hash || ''} />,
              extra: <Button type="link">{ethers.utils.formatEther(item.value)}{ walletState.nativeSymbol }</Button>,
              children: <div className="grid grid-cols-3 gap-[10px]">
                <div>
                  交易哈希：<Address ellipsis tooltip={true} address={item.hash || ''} />
                </div>
                <div>
                  发送地址：<Address ellipsis tooltip={true} address={item.from || ''} />
                </div>
                <div>
                  接受地址：<Address ellipsis tooltip={true} address={item.to || ''} />
                </div>
                <div>
                  发送金额：{ethers.utils.formatEther(item.value)}{ walletState.nativeSymbol }
                </div>
                <div>
                  gas金额：{ethers.utils.formatEther(item.gasPrice || 0)}{ walletState.nativeSymbol }
                </div>
                <div>
                  区块号：{item.blockNumber || ''}
                </div>
                <div>
                  区块hash：<Address ellipsis tooltip={true} address={item.blockHash || ''} />
                </div>
              </div>
            }
          })} defaultActiveKey={['1']}  />
        </Card>
        <TransactionCoin getTransactionList={getTransactionList} ref={TransactionCoinRef}  />
      </div>
      <div className="flex-1"></div>
    </div>
  </>
}
export default Index